package com.leyou.controller;

import com.leyou.common.utils.CookieUtils;
import com.leyou.config.JwtProperties;
import com.leyou.pojo.UserInfo;
import com.leyou.service.AuthService;
import com.leyou.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@EnableConfigurationProperties(JwtProperties.class)
public class AuthController {
    @Autowired
    private AuthService authService;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 登录授权
     *
     * @param username
     * @param password
     * @return
     */
    @PostMapping("accredit")
    public ResponseEntity<Void> accredit(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            HttpServletResponse response,
            HttpServletRequest request) {
        String token = this.authService.accredit(username, password);
        if (token != null) {
            //以上的代码可以使用工具类代替
            CookieUtils.setCookie(request, response, jwtProperties.getCookieName(), token, jwtProperties.getCookieMaxAge(), null, true);
            return ResponseEntity.status(HttpStatus.OK).build();
        }
        //UNAUTHORIZED:表示未授权的
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
    }

    //当用户登录以后,前端会再次发送请求,携带token,对token进行解析得到响应的userInfo(使用userInfo就可以了)展示在前端.
    @GetMapping("verify")
    public ResponseEntity<UserInfo> verify(@CookieValue("LY_TOKEN") String token,
                                           HttpServletRequest request,
                                           HttpServletResponse response) {
        try {
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
            if (userInfo != null) {
                try {
                    //当拿到之后表示成功了,刷新token,每个页面中都有一个shortcuts,每次都会发送verify的请求
                    String newToken = JwtUtils.generateToken(userInfo, jwtProperties.getPrivateKey(), jwtProperties.getExpire());
                    //将新生成的token,通过cookie携带回去
                    CookieUtils.setCookie(request, response, "LY_TOKEN", newToken, jwtProperties.getCookieMaxAge(), null, true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return ResponseEntity.ok(userInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
    }
}
